from flask import Blueprint, jsonify, request
from voluptuous import Schema, Required, All, Length
import datetime
import copy
import json
from .valid_schemas  import home_schema, tag_schema
from ..service.update_tag import UpdateTag
from ..service.update_all_tag import UpdateAllTag
from ..service.record_request import record_request


main = Blueprint('main', __name__)

"""
Flask request 对象文档 http://flask.pocoo.org/docs/0.12/api/#incoming-request-data
"""

def record(func):
    def wap(*args, **kwargs):
        stime = datetime.datetime.today()

        req_id = int(stime.timestamp()*1000)
        url = request.url
        req_data = copy.copy(request.get_json())
        ip = request.remote_addr
        req_data.update(
                {'id': req_id, 'type': 'in', 'url': url, 'createdAt': stime,
                 'func_name': func.__name__, 'ip': ip})
        record_request(req_data)

        res_data = func(*args, **kwargs)

        ins_data = copy.copy(res_data)
        etime = datetime.datetime.today()
        ins_data.update({'id': req_id, 'type': 'out', 'createdAt': etime, 'func_name': func.__name__})

        record_request(ins_data)
        return jsonify(res_data)
    # 需要改名，否则flask会认为是同一个函数
    wap.__name__ = func.__name__
    return wap


@main.route('/', methods=["GET"])
def home():
    home_schema(request.args)
    return jsonify({"code": 0, "data": request.args.get('name', "")})


@main.route('/raise_error', methods=["GET"])
def raise_error():
    raise 'error'

@main.route('/indicators/common', methods=["POST"])
def common_indicators():
    return jsonify({"code": 0, "data": "Hello World"})

@main.route('/update_tag', methods=["POST"])
@record
def update_tag():
    tag_schema(request.get_json())
    tag_class = UpdateTag(request.get_json())
    tag_class.update_tag()
    return {"code": 0, "data": tag_class.tags_list}

@main.route('/update_all_tag', methods=["POST"])
@record
def update_all_tag():
    tag_class = UpdateAllTag()
    data = tag_class.update_tag()
    return {"code": 0, "data": data}